package freespiritsocial.io.user.weight

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import com.luck.picture.lib.entity.LocalMedia
import freespiritsocial.io.user.R
import freespiritsocial.io.user.base.BaseFragment
import freespiritsocial.io.user.ui.fragment.message.ChatFrag
import freespiritsocial.io.user.util.PictureHelper
import me.hgj.jetpackmvvm.base.fragment.BaseBottomSheetDialogFragment

/**
 * 列表底部弹窗
 */
class PictureDialog(
    val fragment: BaseFragment<*,*>,
    var maxSize: Int = 1,
    private var isShowAll: Boolean = true,
    private val callbacks: (ArrayList<LocalMedia>) -> Unit
): BaseBottomSheetDialogFragment() {

    private val pictureHelper by lazy(LazyThreadSafetyMode.NONE) {
        PictureHelper(fragment,maxSize) {
            callbacks.invoke(it)
            dismissAllowingStateLoss()
        }
    }

    fun setMax(max: Int) {
        maxSize = max
        pictureHelper.maxSize = maxSize
    }

    override fun onCreateView(inflater: LayoutInflater,container: ViewGroup?,savedInstanceState: Bundle?): View? {
        return inflater.inflate(R.layout.dialog_pictrue,container,false)

    }

    override fun onViewCreated(view: View,savedInstanceState: Bundle?) {
        super.onViewCreated(view,savedInstanceState)
        init(view)
    }

    private fun init(view: View) = with(view) {
        findViewById<TextView>(R.id.cancel)?.setOnClickListener {
            dismiss()
        }
        findViewById<TextView>(R.id.take_a_photo)?.setOnClickListener {
            pictureHelper.takePic()
        }
        findViewById<TextView>(R.id.choose_from_album)?.setOnClickListener {
            val cantSelectVideo = fragment !is ChatFrag && pictureHelper.data.isEmpty() && maxSize < 6
            if ((maxSize == 1 && !isShowAll) || cantSelectVideo)
                pictureHelper.openGallery()
            else
                pictureHelper.openGalleryWithVideo()
        }

    }

    fun removeData(path: String): Boolean {
        pictureHelper.data.forEach {
            if (it.compressPath == path || it.realPath == path) {
                pictureHelper.data.remove(it)
                return true
            }
        }
        return false
    }
}